/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * callback.c : 
 * Copyright (C) 2009 Lingtao Pan
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, 
 * Boston, MA 02111-1307, USA.
 */

#include "common.h"



static void* run_chdir (void *data);



void stop_cb (GtkWidget *item, gpointer data)
{
    /* The stop button should be clickable only when the following
     * assertions hold. */
    g_return_if_fail (right_viewer != NULL);
    g_return_if_fail (right_viewer->request != NULL);

    /* If some transfer tasks are undergoing, stop them first. */
    if (transfer != NULL) {
        g_static_mutex_lock (&transfer->structmutex);
        if (gftp_transfer_is_active (transfer)) {  
            transfer->cancel = 1;
            g_static_mutex_unlock (&transfer->structmutex);
            return;
        }
   
        g_static_mutex_unlock (&transfer->structmutex);
    }

    if (right_viewer->request->running) {
        pthread_kill (right_viewer->tid, SIGINT);
    
        if (right_viewer->request->wakeup_main_thread[1] > 0)
            write (right_viewer->request->wakeup_main_thread[1], " ", 1);
    }
}

void download_cb (GtkMenuItem *item, gpointer data)
{
    GList *slist, *ptr;
    GtkTreeModel *model;
    GtkTreeSelection *selection;
    GtkTreeIter iter;
    gftp_file *fle, *newfle;
    gftp_transfer *trans_new;

    if (right_viewer == NULL || right_viewer->request == NULL)
        return;

    if (right_viewer->request->running)
        return;

    selection = gtk_tree_view_get_selection 
                   (GTK_TREE_VIEW(right_viewer->treeview));
    if (selection == NULL)
        return;

    model = gtk_tree_view_get_model (GTK_TREE_VIEW(right_viewer->treeview));
  
    slist = gtk_tree_selection_get_selected_rows (selection, &model);

    trans_new = g_malloc0 (sizeof(gftp_transfer));
    trans_new->fromreq = right_viewer->request;
    trans_new->toreq = left_viewer->request;

    for (ptr=slist; ptr; ptr=ptr->next) {
        gtk_tree_model_get_iter (model, &iter, ptr->data);
        gtk_tree_model_get (model, &iter, COLUMN_FILEENTRY, &fle, -1);
        if (strcmp (fle->file, "..") != 0) {
            newfle = gftp_file_copy (fle);
            trans_new->files = g_list_append (trans_new->files, newfle);
        }
    }
  
    g_list_foreach (slist, (GFunc) gtk_tree_path_free, NULL);
    g_list_free (slist);

    if (trans_new->files != NULL) {
        int state, ret;

        state = transfer_get_state ();
        g_assert (state != TRANSFER_RUNNING);

        if (state == TRANSFER_STOPPED) {
            ret = make_transfer_clear_dialog ();
            if (ret == GTK_RESPONSE_CANCEL)
                return;
        }

        transfer_clear ();
      
        gftpui_generic_thread (transfer_append, trans_new);
        transfer_view_update ();

        transfer_view_on_transfer_started ();
        gftpui_generic_thread (transfer_start, NULL);

        if ( !gftp_request_is_connected (right_viewer->request) ) {
            transfer_view_on_transfer_stopped ();
            gftp_viewer_clear (right_viewer);
            return;
        }

        if (trans_new->toreq == right_viewer->request)
            refresh_viewer (right_viewer);
        else
            refresh_viewer (left_viewer);
        transfer_view_on_transfer_stopped ();
    }
}

void upload_cb (GtkMenuItem *item, gpointer data)
{
    GList *slist, *ptr;
    GtkTreeModel *model;
    GtkTreeSelection *selection;
    GtkTreeIter iter;
    gftp_file *fle, *newfle;
    gftp_transfer *trans_new;

    if (right_viewer == NULL || right_viewer->request == NULL)
        return;

    if (right_viewer->request->running)
        return;

    selection = gtk_tree_view_get_selection 
        (GTK_TREE_VIEW(left_viewer->treeview));
    if (selection == NULL)
        return;

    model = gtk_tree_view_get_model (GTK_TREE_VIEW(left_viewer->treeview));
  
    slist = gtk_tree_selection_get_selected_rows (selection, &model);

    trans_new = g_malloc0 (sizeof(gftp_transfer));
    trans_new->fromreq = left_viewer->request;
    trans_new->toreq = right_viewer->request;

    for (ptr=slist; ptr; ptr=ptr->next) {
        gtk_tree_model_get_iter (model, &iter, ptr->data);
        gtk_tree_model_get (model, &iter, COLUMN_FILEENTRY, &fle, -1);
        if (strcmp (fle->file, "..") != 0) {
            newfle = gftp_file_copy (fle);
            trans_new->files = g_list_append (trans_new->files, newfle);
        }
    }
  
    g_list_foreach (slist, (GFunc) gtk_tree_path_free, NULL);
    g_list_free (slist);

    if (trans_new->files != NULL) {
        gftpui_generic_thread (transfer_append, trans_new);
        transfer_view_update ();

        transfer_view_on_transfer_started ();
        gftpui_generic_thread (transfer_start, NULL);

        if ( !gftp_request_is_connected (right_viewer->request) ) {
            gftp_viewer_clear (right_viewer);
            return;
        }

        if (trans_new->toreq == right_viewer->request)
            refresh_viewer (right_viewer);
        else
            refresh_viewer (left_viewer);
        transfer_view_on_transfer_stopped ();
    }
}



void refresh_left_cb (GtkMenuItem *item, gpointer data)
{
    refresh_left ();
}

void refresh_right_cb (GtkMenuItem *item, gpointer data)
{
    refresh_right ();
}

void openurl_edit_finish_cb (GtkEntry *entry, gpointer data)
{
    char *host;
    char *port_s;
    char *username;
    const char *password;
    gftp_request *request;
    int port, protocol;

    request = right_viewer->request;

    /* if already running */
    if (request && request->running) {
        /* show a dialog */
        return;
    } else if (request != NULL) {
        gftp_request_disconnect (request);
        gftp_request_destroy (request, TRUE);
        transfer_clear ();
    }


    host = gtk_combo_box_get_active_text 
               (GTK_COMBO_BOX (gftp_interface->hostedit));
    port_s = gtk_combo_box_get_active_text 
               (GTK_COMBO_BOX (gftp_interface->portedit));
    username = gtk_combo_box_get_active_text 
               (GTK_COMBO_BOX (gftp_interface->useredit));
    password = gtk_entry_get_text (GTK_ENTRY (gftp_interface->passedit));


    right_viewer->request = gftp_request_new (ftp_log_gui);
  
    protocol = get_selected_protocol ();

    if (gftp_protocols[protocol].init (right_viewer->request) != 0) {
        g_error ("protocol %d init error\n", protocol);
        return;
    }

  /* transfer->fromreq = right_viewer->request; */ 

    if (strstr (host, "://") != NULL)
        gftp_request_parse_url (right_viewer->request, host);
    else {
        gftp_request_set_hostname (right_viewer->request, host);
        gftp_request_set_username (right_viewer->request, username);
        gftp_request_set_password (right_viewer->request, password);
        port = atoi(port_s);
        gftp_request_set_port (right_viewer->request, port);
    }
    
    on_viewer_connecting (right_viewer);
    enable_progressbar (gftp_interface);
    gftpui_generic_thread (perform_connection, NULL);
    disable_progressbar (gftp_interface);

    if (gftp_request_is_connected (right_viewer->request)) {
        gftp_viewer_combo_set_text_no_emission (right_viewer, 
                                  right_viewer->request->directory);
        gftp_viewer_show_files (right_viewer);
        on_viewer_connected (right_viewer);
    }
}


void delete_file_left_cb (GtkMenuItem *item, gpointer data)
{
    GList *slist, *ptr;
    GtkTreeModel *model;
    GtkTreeSelection *selection;
    GtkTreeIter iter;
    gftp_file *fle;

    selection = gtk_tree_view_get_selection 
        (GTK_TREE_VIEW(left_viewer->treeview));
    if (selection == NULL)
        return;

    model = gtk_tree_view_get_model (GTK_TREE_VIEW(left_viewer->treeview));
  
    slist = gtk_tree_selection_get_selected_rows (selection, &model);

    for (ptr=slist; ptr; ptr=ptr->next) {
        gchar *filename;
        gtk_tree_model_get_iter (model, &iter, ptr->data);
        gtk_tree_model_get (model, &iter, COLUMN_FILEENTRY, &fle, -1);

        filename = gftp_build_path (left_viewer->request, 
                                    left_viewer->request->directory, 
                                    fle->file, NULL);
        if (S_ISDIR(fle->st_mode))
            gftp_request_remove_directory (left_viewer->request, filename);
        else
            gftp_request_remove_file (left_viewer->request, filename);
        g_free (filename);
    }

    g_list_foreach (slist, (GFunc) gtk_tree_path_free, NULL);
    g_list_free (slist);

    refresh_left ();
}

void delete_file_right_cb (GtkMenuItem *item, gpointer data)
{
    
}

void viewer_row_activated_cb (GtkTreeView *treeview, GtkTreePath *path,
                    GtkTreeViewColumn *column, gpointer data)
{
    Viewer *viewer = (Viewer *) data;
    GtkTreeModel *model;
    GtkTreeIter iter;
    gftp_file *fle;
    char *directory;
    char *tempstr;
    int pos;

    if (transfer_get_state() == TRANSFER_RUNNING)
        return;

    if (viewer == right_viewer && right_viewer->request->running)
        return;

    model = gtk_tree_view_get_model (treeview);
    if (gtk_tree_model_get_iter (model, &iter, path) == FALSE)
    {
        /* Handle the selection */
        g_debug ("tree model get iter error\n");
        return;
    }

    gtk_tree_model_get (model, &iter, COLUMN_FILEENTRY, &fle, -1);
    g_assert (fle != NULL);
  
    if (!S_ISDIR (fle->st_mode) && !S_ISLNK (fle->st_mode))
        return;

    pos = gtk_tree_path_get_indices (path)[0];
    gftp_viewer_add_directory_history (viewer, viewer->request->directory, pos);

    directory = gftp_build_path (viewer->request, viewer->request->directory,
                                 fle->file, NULL);
    tempstr = gftp_expand_path (directory);
    if (tempstr == NULL) {
        dprintf ("gftp_expand_path fails");
        g_free (directory);
    }

  
    /* This will triger viewer_directory_edited_cb(). So we don't have
     * to call run_chdir() here.
     */
    gftp_viewer_combo_set_text (viewer, tempstr);
  

    g_free (directory);
    g_free (tempstr);
}

void
viewer_directory_edited_cb (GtkEntry *entry, Viewer *viewer)
{
    gchar *dir;
    int pos;

    if (viewer->request == NULL || !gftp_request_is_connected (viewer->request) 
        || viewer->request->running)
        return;


    dir = gtk_combo_box_get_active_text (GTK_COMBO_BOX (viewer->combo));
    viewer->request->user_data = dir;

    pos = gftp_viewer_get_tree_view_position (viewer);
    gftp_viewer_add_directory_history (viewer, viewer->request->directory, pos);
    
    if (viewer == right_viewer) {
        enable_progressbar (gftp_interface);
        gftpui_generic_thread (run_chdir, viewer); 
        disable_progressbar (gftp_interface);

        if ( !gftp_request_is_connected (right_viewer->request) ) {
            gftp_viewer_clear (right_viewer);
            return;
        }

        gftp_viewer_show_files (viewer);
    } else {
        run_chdir (viewer);
        gftp_viewer_show_files (viewer);
    }

    /* update_status_bar (viewer); */
}

void
viewer_combo_changed_cb (GtkComboBox *combo, Viewer *viewer)
{
    gboolean focus;
    gchar *dir;


    if (viewer->request == NULL || !gftp_request_is_connected (viewer->request) 
        || viewer->request->running)
        return;


    focus = gtk_widget_is_focus ( GTK_WIDGET (
                          gtk_bin_get_child (GTK_BIN(combo))) );

    if (focus)                  /* the user is editing */
        return;

    dir = gtk_combo_box_get_active_text (GTK_COMBO_BOX (viewer->combo));
    viewer->request->user_data = dir;
    
    if (viewer == right_viewer) {
        enable_progressbar (gftp_interface);
        gftpui_generic_thread (run_chdir, viewer);
        disable_progressbar (gftp_interface);
        if ( !gftp_request_is_connected (right_viewer->request) ) {
            gftp_viewer_clear (right_viewer);
            return;
        }

        gftp_viewer_show_files (viewer);
    } else {
        run_chdir (viewer);
        gftp_viewer_show_files (viewer);
    }
}

/* void */
/* cb_viewer_combo_popup (GtkComboBox *combo, Viewer *viewer) */
/* { */
/*     dprintf ("combo popup\n"); */
/* } */

/* void */
/* cb_viewer_combo_popdown (GtkComboBox *combo, Viewer *viewer) */
/* { */
/*     dprintf ("combo popdown\n"); */
/* } */


static void
do_popup_right_view_menu (GtkWidget *my_widget, GdkEventButton *event)
{
    GtkWidget *popup;
    int button, event_time;
    
    if (event != NULL) {
        button = event->button;
        event_time = event->time;
    } else {
        button = 0;
        event_time = gtk_get_current_event_time ();
    }

    popup = gtk_ui_manager_get_widget (ui_manager, "/RightViewPopup");
    g_assert (popup != NULL);
    gtk_menu_popup (GTK_MENU (popup), NULL, NULL, NULL, NULL,
                    button, event_time);

}


gboolean
right_view_button_click_cb (GtkWidget *widget, GdkEventButton *event, 
                            gpointer data)
{
  if ((event->button == 3 ) && (event->type == GDK_BUTTON_PRESS)) {
      do_popup_right_view_menu (widget, event);
    return TRUE;
  }

  return FALSE;         
}


static void
do_popup_left_view_menu (GtkWidget *my_widget, GdkEventButton *event)
{
    GtkWidget *popup;
    int button, event_time;
    
    if (event != NULL) {
        button = event->button;
        event_time = event->time;
    } else {
        button = 0;
        event_time = gtk_get_current_event_time ();
    }

    popup = gtk_ui_manager_get_widget (ui_manager, "/LeftViewPopup");
    g_assert (popup != NULL);
    gtk_menu_popup (GTK_MENU (popup), NULL, NULL, NULL, NULL,
                    button, event_time);

}

gboolean
left_view_button_click_cb (GtkWidget *widget, GdkEventButton *event, 
                            gpointer data)
{
  if ((event->button == 3 ) && (event->type == GDK_BUTTON_PRESS)) {
      do_popup_left_view_menu (widget, event);
    return TRUE;
  }

  return FALSE;
}

gboolean
viewer_popup_menu_cb (GtkWidget *widget, Viewer *viewer)
{
    if (viewer == left_viewer) {
        do_popup_left_view_menu (widget, NULL);
    } else {
        do_popup_right_view_menu (widget, NULL);
    }
    return TRUE;
}



static void* run_chdir (void *data)
{
  int ret;
  Viewer *viewer = data;
  gchar *lastdir, *newdir;

  lastdir = g_strdup (viewer->request->directory);
  newdir = (gchar *) viewer->request->user_data;
  ret = gftp_request_set_directory (viewer->request, newdir);

  if (ret < 0) {
      gftp_request_set_directory (viewer->request, lastdir);
      g_free (lastdir);
      return NULL;
  }

  gftp_viewer_get_file_list (viewer);
  /* gftp_viewer_combo_set_text (viewer, newdir); */
  
  g_free (lastdir);

  return NULL;
}


void copy_filename_left_cb (GtkMenuItem *item, gpointer data)
{
    gftp_viewer_copy_filename (left_viewer);
}

void copy_filename_right_cb (GtkMenuItem *item, gpointer data)
{
    gftp_viewer_copy_filename (right_viewer);
}


gboolean viewer_enter_leave_cb (GtkWidget *widget, GdkEventCrossing *event,
                              Viewer *viewer)
{
    guint id;
    gchar *tempstr, *space_str;
    guint64 space;
    GtkStatusbar *bar = gftp_interface->statusbar;

    id = gtk_statusbar_get_context_id (bar, "ViewerStatus");

    if (viewer == left_viewer) {
        if (event->type == GDK_ENTER_NOTIFY) {
            space = get_disk_free_space (left_viewer->request->directory);
            space_str = g_format_size_for_display ((goffset) space); 
            tempstr = g_strdup_printf (_("Local Free Space: %s"), space_str);
            gtk_statusbar_push (bar, id, tempstr);

            g_free (space_str);
            g_free (tempstr);
        } else if (event->type == GDK_LEAVE_NOTIFY) {
            gtk_statusbar_pop (bar, id);
        }
    }
    
    return FALSE;
}

void
show_help_cb (GtkMenuItem *item, gpointer data)
{
    
}

void
show_about_cb (GtkMenuItem *item, gpointer data)
{
	static const char *authors[] = {
		"Lingtao Pan <freeplant@gmail.com>",
		NULL
	};

	const char *license[] = {
		N_("This program is free software; you can redistribute it and/or modify "
		   "it under the terms of the GNU General Public License as published by "
		   "the Free Software Foundation; either version 2 of the License, or "
		   "(at your option) any later version.\n"),
		N_("This program is distributed in the hope that it will be useful, "
		   "but WITHOUT ANY WARRANTY; without even the implied warranty of "
		   "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the "
		   "GNU General Public License for more details.\n"),
		N_("You should have received a copy of the GNU General Public License "
		   "along with this program; if not, write to the Free Software "
		   "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.")
	};

	char *license_trans;

	license_trans = g_strconcat (_(license[0]), "\n", _(license[1]), "\n",
				     _(license[2]), "\n", NULL);


	gtk_show_about_dialog (GTK_WINDOW (gftp_interface->window),
			       "program-name", _("gftp2"),
			       "version", VERSION,
			       "copyright", "Copyright \xc2\xa9 2009 THOSS",
			       "comments",_("gftp2: ftp client based on gftp."),
			       "authors", authors,
			       "logo-icon-name", "gftp",
			       "wrap-license", TRUE,
			       "license", license_trans,
			       NULL);

	g_free (license_trans);    
}


void
bookmark_activated_cb (GtkMenuItem *menu_item, gftp2_bookmark *bm)
{
    char buf[10];
    snprintf (buf, 10, "%d", bm->port); 

    if (!bm->hostname)
        return;

    gtk_entry_set_text (
        GTK_ENTRY(gtk_bin_get_child(GTK_BIN (gftp_interface->hostedit))),
        bm->hostname);
    gtk_entry_set_text (
        GTK_ENTRY(gtk_bin_get_child(GTK_BIN (gftp_interface->portedit))),
        buf);
    gtk_entry_set_text (
        GTK_ENTRY(gtk_bin_get_child(GTK_BIN (gftp_interface->useredit))),
        bm->user ? bm->user : "");
    if (bm->passwd)
        gtk_entry_set_text (GTK_ENTRY (gftp_interface->passedit), 
                            bm->passwd ? bm->passwd : "");

    openurl_edit_finish_cb (NULL, NULL);
}
